package com.hanter.android.safdemo

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModelProvider
import com.hanter.android.saf.SafManager

class MainActivity : AppCompatActivity(), View.OnClickListener {

    var uri: Uri? = null
    private lateinit var mainViewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        mainViewModel.register(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_permission -> {

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        ), 1
                    )
                } else {
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                        ), 1
                    )
                }
            }

            R.id.btn_create -> {
//                writeUri(mainViewModel.createImageUri("test.jpg"))
//                writeUri(mainViewModel.createMediaUri(Environment.DIRECTORY_DCIM, "test.jpg"))
//                writeUri(safm.createMediaUri(Environment.DIRECTORY_DCIM, "test.jpg"))
//                writeUri(safm.createMediaUri(Environment.DIRECTORY_PICTURES, "test.jpg"))
//                writeUri(safm.createMediaUri(Environment.DIRECTORY_MUSIC, "testd.mp3"))

//                writeUri(safm.createMediaUri(Environment.DIRECTORY_MOVIES, "test.mp4"))

                mainViewModel.createMediaUri(SafManager.DIRECTORY_AUDIOBOOKS, "asfas/test.mp3")?.let { uri ->
                    writeUri(uri)
                }
            }

            R.id.btn_get -> {
                if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    // 判断权限是否有读取存储权限
                    return
                }

                uri = mainViewModel.getMediaUri(SafManager.DIRECTORY_AUDIOBOOKS, "asfas/test.mp3")
//                uri = mainViewModel.getMediaUri(Environment.DIRECTORY_DCIM, "test.jpg")
                Toast.makeText(this, "uri: $uri", Toast.LENGTH_SHORT).show()
            }

            R.id.btn_exists -> {
                // 创建文件
                /*
                if (safm.exists(Environment.DIRECTORY_PICTURES, "test.jpg")) {
                    Toast.makeText(this, "test.jpg 存在", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "test.jpg 不存在", Toast.LENGTH_SHORT).show()
                }
                */

                if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    // 判断权限是否有读取存储权限
                    return
                }

                if (mainViewModel.exists(SafManager.DIRECTORY_AUDIOBOOKS, "asfas/test.mp3")) {
//                if (mainViewModel.exists(Environment.DIRECTORY_DCIM, "test.jpg")) {
                    Toast.makeText(this, "存在", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "不存在", Toast.LENGTH_SHORT).show()
                }
            }

            R.id.btn_delete -> {
                // 删除文件
                uri ?: return

                if (mainViewModel.delete(uri!!)) {
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "删除不成功", Toast.LENGTH_SHORT).show()
                }
            }

            R.id.btn_delete_callback -> {
                uri ?: return

                mainViewModel.delete(uri!!) { deleted ->
                    Toast.makeText(this@MainActivity, "result: $deleted", Toast.LENGTH_SHORT)
                        .show()
                }
            }

            R.id.btn_delete_row_id -> {
                uri?.let {
                    contentResolver.query(
                        it,
                        arrayOf(
                            MediaStore.MediaColumns._ID
                        ),
                        null,
                        null,
                        null
                    )?.use { cursor ->
                        if (cursor.moveToFirst()) {
                            val id = cursor.getLong(0)
                            mainViewModel.delete(MediaStore.Files.getContentUri("external"), id)
                        }
                    }
                }
            }
        }
    }

    class

    private fun writeUri(uri: Uri?) {
        this.uri = uri ?: return

        val cursor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            contentResolver.query(uri,
                arrayOf(
                    MediaStore.MediaColumns.DISPLAY_NAME,
                    MediaStore.MediaColumns.RELATIVE_PATH
                ),
                null,
                null,
                null
            )
        } else {
            contentResolver.query(uri,
                arrayOf(
                    MediaStore.MediaColumns.DISPLAY_NAME,
                    MediaStore.MediaColumns.DATA
                ),
                null,
                null,
                null
            )
        }
        cursor?.use {
            if (cursor.moveToFirst()) {
                Log.d("Test", "name: ${cursor.getString(0)}")
                Log.d("Test", "path: ${cursor.getString(1)}")
            }
        }

        contentResolver.openOutputStream(uri)?.use {
            it.write("123456".toByteArray())
        }
    }

}